<template>
  <!-- 基础信息 -->
  <a-card class="box">
    <a-form layout="vertical">
      <a-row>
        <a-col :span="formSpan" :offset="formOffset">
          <a-form-item label="图标" v-bind="validateInfos.icon">
            <div>
              <a-avatar :src="formState.icon" :size="48" />
              <a-popover
                v-model:visible="changeIconVisible"
                placement="rightBottom"
                title="请选择图标"
                trigger="click"
              >
                <template #content>
                  <a-row :gutter="[12, 0]" style="width: 360px">
                    <a-col
                      class="icon-box"
                      :span="4"
                      v-for="(item, index) of iconList"
                      :key="index"
                      @click="changeIcon(item)"
                    >
                      <a-avatar :src="item" :size="42" />
                    </a-col>
                  </a-row>
                </template>
                <a-button type="link" @click="changeIconVisible = true">
                  修改
                </a-button>
              </a-popover>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="formSpan" :offset="formOffset">
          <a-form-item label="名称" v-bind="validateInfos.name">
            <a-input v-model:value="formState.name" placeholder="请输入名称" />
          </a-form-item>
        </a-col>
        <a-col :span="formSpan" :offset="formOffset">
          <a-form-item label="说明">
            <a-textarea
              v-model:value="formState.desc"
              placeholder="请输入说明"
              :row="2"
            />
          </a-form-item>
        </a-col>
        <a-col :span="formSpan" :offset="formOffset">
          <a-form-item label="分组" v-bind="validateInfos.cat_id">
            <a-select
              v-model:value="formState.cat_id"
              :options="catList"
              placeholder="请选择分组"
            />
          </a-form-item>
        </a-col>
        <a-col :span="formSpan" :offset="formOffset">
          <a-form-item >
            <template #label>
              <div>
                <span class="mr-5">页面展示封面图</span>
                <a-tooltip placement="top">
                  <template #title>用户打开发起审批页面后，页面会首先展示此图。您可以用来做页面美化，也可以展示注意事项使用，或者您认为合理的其他一些用途</template>
                  <span><QuestionCircleOutlined /></span>
                </a-tooltip>
              </div>
            </template>
            <div style="display: flex;">
              <div >
                <a-upload
                    v-model:file-list="fileList"
                    name="avatar"
                    list-type="picture-card"
                    class="avatar-uploader"
                    :show-upload-list="false"
                    action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                    @change="handleChanges"
                    accept="image/jpg,image/jpeg,image/gif,image/png"
                >
                  <div v-if="formState.banner_img" style="width: 100%;height: 100%;position: relative;">
                    <div @click.stop.prevent="deletees"  style="position: absolute;top: -10px;right: -4px;color: red;font-size: 16px"><CloseCircleFilled /></div>
                    <a-popover >
                      <template #content>
                        <div>
                          <img :src="formState.banner_img" class="previewImg">
                        </div>
                      </template>
                      <img :src="formState.banner_img" class="img-viewes">
                    </a-popover>
                  </div>
                  <div v-else>
                    <loading-outlined v-if="loadinges"></loading-outlined>
                    <plus-outlined v-else></plus-outlined>
                    <div class="ant-upload-text">上传图片</div>
                  </div>
                </a-upload>
              </div>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="formSpan" :offset="formOffset">
          <a-form-item
            v-bind="validateInfos.start_user_type"
          >
            <template #label>
              <div>
                <span class="mr-5">谁可以发起这个审批</span>
                <a-tooltip placement="top" v-if="!!approvalDetail.alias&&formState.start_user_type==2">
                  <template #title>该审批由【{{ approvalDetail.from_third }}】发起审批，不支持直接发起审批。</template>
                  <span><QuestionCircleOutlined /></span>
                </a-tooltip>
              </div>
            </template>
            <div>
              <a-select
                :options="common.memberOptions"
                v-model:value="formState.start_user_type"
                @change="handleApprovalMemberSelect"
                :disabled="!!approvalDetail.alias"
              />
              <a-row
                class="mt-10 user-tag"
                align="middle"
                v-if="showApprovalMember"
              >
                <a-tag
                  closable
                  v-for="(department, index) of launchApprovalMember.department"
                  :key="department.id"
                  @close="approvalMemberRemove('department', index)"
                  style="margin: 5px 10px 5px 0"
                >
                  <a-avatar style="color: #fff; background-color: #2681f3">
                    <template #icon><PartitionOutlined /></template>
                  </a-avatar>
                  <span class="ml-10"> {{ department.name }} </span>
                </a-tag>
                <a-tag
                  closable
                  v-for="(user, index) of launchApprovalMember.user"
                  :key="user.uid"
                  @close="approvalMemberRemove('user', index)"
                  style="margin: 5px 10px 5px 0"
                >
                  <a-avatar
                    :src="user.avatar"
                    style="color: #fff; background-color: #2681f3"
                  >
                    <template #icon><UserOutlined /></template>
                  </a-avatar>
                  <span class="ml-10"> {{ user.realname }} </span>
                </a-tag>
                <a-button
                  class="ml-10"
                  type="primary"
                  ghost
                  @click="handleApprovalMemberSelect"
                >
                  添加
                </a-button>
              </a-row>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="formSpan" :offset="formOffset">
          <a-form-item label="流程管理员" v-bind="validateInfos.admin_users">
            <a-row align="middle" class="user-tag">
              <a-tag
                closable
                v-for="(user, index) of approvalAdmin.user"
                :key="user.uid"
                @close="approvalAdminRemove(index)"
                style="margin: 5px 10px 5px 0"
              >
                <a-avatar
                  :src="user.avatar"
                  style="color: #fff; background-color: #2681f3"
                >
                  <template #icon><UserOutlined /></template>
                </a-avatar>
                <span class="ml-10"> {{ user.realname }} </span>
              </a-tag>
              <a-button type="primary" ghost @click="chooseMemberType = 2">
                添加
              </a-button>
            </a-row>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <!-- 选择人员 -->
    <ChooseOrgMember
      @request="$utils.commonRequest"
      :visible="!!chooseMemberType"
      :deptDisabled="chooseMemberType == 2"
      :getDetail="true"
      :checkedList="memberCheckedList"
      @close="handleChooseMemberClose"
      @success="handleChooseMemberSuccess"
    />
  </a-card>
</template>

<script>
import { computed, defineComponent, reactive, toRefs, watch } from "vue";
import request from "../../../../common/utils/request";
import { ChooseOrgMember } from "bl-common-vue3";
import {
  CloseCircleFilled, LoadingOutlined,
  PartitionOutlined,
  PlusOutlined,
  QuestionCircleOutlined,
  UserOutlined
} from "@ant-design/icons-vue";
import store from "../../../../store";
import common from "../js/common";
import { Form } from "ant-design-vue";
import { useRoute } from "vue-router";
import utils from "@/common/utils/utils";
const useForm = Form.useForm;

export default defineComponent({
  name: "BasicInfo",
  components: {
    LoadingOutlined,
    CloseCircleFilled, QuestionCircleOutlined, PlusOutlined,
    PartitionOutlined,
    UserOutlined,
    ChooseOrgMember,
  },
  props: {
    trigger: {
      type: Number,
      default: 0,
    },
  },
  setup(props, { emit }) {
    const route = useRoute();

    const state = reactive({
      id: route.query.id,
      formSpan: 16,
      formOffset: 4,
      iconList: [],
      changeIconVisible: false,
      catList: [],
      showApprovalMember: false,
      chooseMemberType: 0, // 发起选择人员、部门弹窗的type : 1谁可以发起这个审批 2流程管理员
      launchApprovalMember: { user: [], department: [] },
      approvalAdmin: { user: [], department: [] },
      fileList:[],
      loadinges: false
    });
    // 选择人员弹窗回显数据
    const memberCheckedList = computed(() => {
      let user = [];
      let department = [];
      if (state.chooseMemberType == 1) {
        user = state.launchApprovalMember.user.map((item) => item.uid);
        department = state.launchApprovalMember.department.map(
          (item) => item.id
        );
      }
      if (state.chooseMemberType == 2) {
        user = state.approvalAdmin.user.map((item) => item.uid);
      }
      return { user, department };
    });

    // 表单
    const formState = reactive({
      icon: "", // 图标
      name: "", // 审批名称
      desc: "", // 说明
      cat_id: undefined, // 分组
      start_user_type: 0, // 谁可以发起审批
      admin_users: [],
      banner_img: "",
    });
    const requiredRule = [{ required: true, message: "必填项" }];
    const formRule = reactive({
      name: requiredRule,
      cat_id: requiredRule,
      icon: requiredRule,
      start_user_type: requiredRule,
      admin_users: requiredRule,
    });
    const { resetFields, validate, validateInfos } = useForm(
      formState,
      formRule
    );

    // 图标
    const changeIcon = (icon) => {
      formState.icon = icon;
      state.changeIconVisible = false;
    };
    const getIcons = () => {
      request
        .get("/work_approval", "/manage/approval/systemIcons")
        .then((res) => {
          state.iconList = res.list;
          if (!state.id) {
            changeIcon(res.list[0]);
          }
        });
    };

    // 分类
    const getCats = () => {
      request
        .get("/work_approval", "/manage/category", {
          withApproval: 0,
        })
        .then((res) => {
          state.catList = res.list.map((item) => ({
            label: item.cat_name,
            value: item.id,
          }));
        });
    };

    // 谁发起这个审批
    const handleApprovalMemberSelect = () => {
      if (formState.start_user_type == 1) {
        state.chooseMemberType = 1;
        state.showApprovalMember = true;
      } else {
        //指定人员可发起时才显示人员列表
        state.showApprovalMember = false;
      }
    };
    const approvalMemberRemove = (type, index) => {
      state.launchApprovalMember[type].splice(index, 1);
      if (!hasSelecedMember(state.launchApprovalMember)) {
        handleChooseMemberClose();
        state.showApprovalMember = false;
      }
    };
    const approvalAdminRemove = (index) => {
      state.approvalAdmin.user.splice(index, 1);
    };

    // 选择人员
    // 是否已经选择了人员
    const hasSelecedMember = (detail) => {
      return detail.user.length || detail.department.length;
    };
    // 关闭
    const handleChooseMemberClose = () => {
      // 没有选择人员发起审批
      if (
        formState.start_user_type == 1 &&
        !hasSelecedMember(state.launchApprovalMember)
      ) {
        formState.start_user_type = 2;
      }
      state.chooseMemberType = 0;
    };
    // 确认
    const handleChooseMemberSuccess = (detail) => {
      console.log("-------------handleChooseMemberSuccess", detail);
      if (hasSelecedMember(detail)) {
        if (state.chooseMemberType == 1) {
          state.launchApprovalMember = detail;
          state.showApprovalMember = true;
        }
        if (state.chooseMemberType == 2) {
          state.approvalAdmin = detail;
        }
      }
      handleChooseMemberClose();
    };

    const validateForm = () => {
      if (formState.start_user_type == 1) {
        formState.start_users = {
          users: state.launchApprovalMember.user.map((item) => item.uid),
          depart: state.launchApprovalMember.department.map((item) => item.id),
        };
      }
      if (state.approvalAdmin.user.length) {
        formState.admin_users = state.approvalAdmin.user.map((item) => ({
          uid: item.uid,
          auth: [],
        }));
      }

      validate();

      let params = {
        ...formState,
        adminUserList: state.approvalAdmin.user.map((item) => ({
          label: item.realname,
          value: item.uid,
        })),
      };

      store.dispatch("SetBasicInfo", params).then(() => {
        emit("triggerChange", params);
      });
    };

    const approvalDetail = computed(() => store.getters.approvalDetail);

    const handleChanges = (info) => {
      state.loadinges = true
      state.fileList = info.fileList.filter((item) => item.url);
      getBase64(info.file.originFileObj, (imageUrl) => {
        request.post("/public", "/system/uploadImageFromBase64", {
          image: imageUrl,
          dir: "pass_photo",
        }).then((res) => {
          formState.banner_img = res.fileUrl
          state.loadinges = false
        });
      });
    }

    const getBase64 = (img, callback) => {
      if (img) {
        const reader = new FileReader();
        reader.addEventListener("load", () => callback(reader.result));
        reader.readAsDataURL(img);
      }
    }

    const deletees = () => {
      formState.banner_img = ''
    }

    const init = () => {
      let data = JSON.parse(utils.getStorage("approval_id"))
      state.id = route.query?.id ? route.query.id : data?.id?data.id:undefined
      getIcons();
      getCats();
      if (state.id) {
        watch(
          () => approvalDetail.value,
          (detail) => {
            console.log("------------basic info init", detail);
            if (detail && detail.id) {
              formState.icon = detail.icon;
              formState.name = detail.name;
              formState.desc = detail.desc;
              formState.cat_id = detail.cat_id;
              formState.start_user_type = detail.start_user_type;
              state.approvalAdmin.user = detail.admin_users;
              formState.banner_img = detail.banner_img;
              if (formState.start_user_type == 1) {
                state.launchApprovalMember = {
                  user: detail.start_users.users,
                  department: detail.start_users.depart,
                };
                state.showApprovalMember = true;
              }
            }
          }
        );
      } else {
        const userInfo = store.getters.userInfo;
        if (userInfo.uid) {
          state.approvalAdmin.user.push({
            uid: userInfo.uid,
            realname: userInfo.realname,
            avatar: userInfo.avatar,
          });
        }
      }
    };

    init();

    watch(
      () => props.trigger,
      () => {
        validateForm();
      }
    );
    return {
      formState,
      validateInfos,
      common,
      memberCheckedList,
      approvalDetail,
      ...toRefs(state),
      changeIcon,
      handleApprovalMemberSelect,
      handleChooseMemberClose,
      handleChooseMemberSuccess,
      approvalMemberRemove,
      approvalAdminRemove,
      handleChanges,
      getBase64,
      deletees,
    };
  },
});
</script>
<style lang="less" scoped>
.box {
  width: 80%;
  margin: 20px auto;
}
.icon-box {
  width: 55px;
  height: 55px;
  display: flex;
  align-items: center;
  justify-content: center;
  // border: 1px solid #f1f1f1;
  border-radius: 4px;
  cursor: pointer;
}
.user-tag {
  :deep(.ant-tag) {
    border-radius: 20px !important;
    padding: 0 12px 0 0 !important;
    background: #f1f1f1;
    border: none;
  }
}
.previewImg{
  max-width: 400px;
}
.img-viewes{
  width: 86px;
  height: 86px;
  object-fit: cover;
  border-radius: 5px;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.mr-5{
  margin-right: 5px;
}
</style>
